const { createApp } = Vue

// 配置 axios 默认值和拦截器
axios.defaults.baseURL = '/api';

// 请求拦截器
axios.interceptors.request.use(config => {
    const token = localStorage.getItem('token');
    if (!token) {
        window.location.href = '/login.html';
        return Promise.reject('未登录');
    }
    config.headers['Authorization'] = token;
    return config;
}, error => {
    return Promise.reject(error);
});

// 响应拦截器
axios.interceptors.response.use(
    response => response,
    error => {
        if (error.response?.status === 401) {
            localStorage.removeItem('token');
            window.location.href = '/login.html';
        }
        return Promise.reject(error);
    }
);

createApp({
    data() {
        return {
            showModal: false,
            currentWeek: new Date(),
            timeSlots: [
                '09:00-10:00', '10:00-11:00', '11:00-12:00',
                '14:00-15:00', '15:00-16:00', '16:00-17:00'
            ],
            scheduleForm: {
                date: '',
                timeSlot: '',
                type: 'offline'
            },
            weekStart: '',
            calendarData: [],
            weekDays: [],
            scheduleGrid: [],
            isPastWeek: false
        }
    },
    computed: {
        currentDate() {
            const now = new Date()
            const options = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' }
            return now.toLocaleDateString('zh-CN', options)
        },
        weekDays() {
            const days = []
            const start = this.getWeekStart(this.currentWeek)

            for (let i = 0; i < 7; i++) {
                const date = new Date(start)
                date.setDate(date.getDate() + i)

                days.push({
                    name: this.getWeekdayName(date),
                    date: this.formatDate(date),
                    slots: this.getTimeSlots(date)
                })
            }

            return days
        },
        currentWeekRange() {
            const start = this.getWeekStart(this.currentWeek)
            const end = new Date(start)
            end.setDate(end.getDate() + 6)

            return `${this.formatDate(start)} - ${this.formatDate(end)}`
        }
    },
    methods: {
        getWeekStart(date) {
            const start = new Date(date)
            start.setDate(start.getDate() - start.getDay())
            return start
        },
        getWeekdayName(date) {
            const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
            return weekdays[date.getDay()];
        },
        formatDate(date) {
            return `${date.getMonth() + 1}月${date.getDate()}日`
        },
        formatDateForInput(date) {
            const year = date.getFullYear()
            const month = String(date.getMonth() + 1).padStart(2, '0')
            const day = String(date.getDate()).padStart(2, '0')
            return `${year}-${month}-${day}`
        },
        getTimeSlots(date) {
            const dateStr = date.toISOString().split('T')[0]
            const today = new Date()
            today.setHours(0, 0, 0, 0)
            const isPastDate = date < today

            return this.timeSlots.map(time => {
                const appointment = this.appointments.find(a =>
                    a.date === dateStr && a.time === time
                )
                return {
                    time,
                    booked: !!appointment,
                    disabled: isPastDate,
                    clientName: appointment?.clientName,
                    type: appointment?.type
                }
            })
        },
        previousWeek() {
            const newDate = new Date(this.currentWeek)
            newDate.setDate(newDate.getDate() - 7)
            this.currentWeek = newDate
            this.weekStart = this.formatDateForInput(this.getWeekStart(this.currentWeek))
            this.checkIsPastWeek()
            this.initializeCalendarData()
            this.fetchWeeklySchedule()
        },
        nextWeek() {
            const newDate = new Date(this.currentWeek)
            newDate.setDate(newDate.getDate() + 7)
            this.currentWeek = newDate
            this.weekStart = this.formatDateForInput(this.getWeekStart(this.currentWeek))
            this.checkIsPastWeek()
            this.initializeCalendarData()
            this.fetchWeeklySchedule()
        },
        showAddScheduleModal() {
            this.showModal = true
        },
        closeModal() {
            this.showModal = false
            this.scheduleForm = {
                date: '',
                timeSlot: '',
                type: 'offline'
            }
        },
        handleSlotClick(day, timeSlot) {
            // 获取对应的时间槽数据
            const dayIndex = this.calendarData.findIndex(d => d.date === day.date);
            const timeIndex = this.timeSlots.indexOf(timeSlot);
            const slot = this.calendarData[dayIndex].slots[timeIndex];

            // 如果时间槽已被预约、已取消或已被选中，则不允许操作
            if (slot.status === 'booked' || slot.status === 'cancelled' || slot.status === 'selected') {
                return;
            }

            // 如果是过去的日期，也不允许操作
            if (this.isPastDate(day.date)) {
                alert('不能修改过去的日期');
                return;
            }

            // 显示添加排班的模态框
            this.scheduleForm.date = day.date;
            this.scheduleForm.timeSlot = timeSlot;
            this.showModal = true;
        },
        initializeCalendarData() {
            this.calendarData = [];
            this.weekDays = [];

            const start = this.getWeekStart(this.currentWeek);

            for (let i = 0; i < 7; i++) {
                const date = new Date(start);
                date.setDate(date.getDate() + i);
                const formattedDate = this.formatDateForInput(date);

                // 更新 weekDays
                this.weekDays.push({
                    name: this.getWeekdayName(date),
                    date: formattedDate,
                    fullDate: formattedDate
                });

                // 更新 calendarData
                this.calendarData.push({
                    date: formattedDate,
                    slots: this.timeSlots.map(() => ({
                        id: null,
                        type: null,
                        status: null,
                        statusText: null,
                        client: null
                    }))
                });
            }
        },
        updateScheduleDisplay(scheduleData) {
            if (!Array.isArray(scheduleData)) {
                console.error('排班数据格式错误:', scheduleData);
                return;
            }

            // 初始化每天的时间槽
            this.calendarData = this.weekDays.map(day => ({
                date: day.fullDate,
                slots: this.timeSlots.map(() => ({
                    type: 'offline',      // 默认为面对面咨询
                    status: 'available',  // 默认状态为空闲
                    statusText: '空闲',
                    client: null
                }))
            }));

            // 更新数据
            scheduleData.forEach(schedule => {
                const dayIndex = this.calendarData.findIndex(day => day.date === schedule.date);
                if (dayIndex === -1) return;

                const timeIndex = this.timeSlots.findIndex(slot =>
                    this.normalizeTimeSlot(slot) === this.normalizeTimeSlot(schedule.timeSlot)
                );
                if (timeIndex === -1) return;

                // 更新对应的时间槽
                this.calendarData[dayIndex].slots[timeIndex] = {
                    type: schedule.type,
                    status: schedule.status,
                    statusText: this.getStatusText(schedule.status),  // 使用 getStatusText 获取状态文本
                    client: schedule.client
                };
            });

            console.log('更新后的日历数据:', this.calendarData);
        },
        getStatusText(status) {
            switch (status) {
                case 'available':
                    return '空闲';
                case 'selected':
                    return '可被约';
                case 'booked':
                    return '已预约';
                case 'cancelled':
                    return '已取消';
                default:
                    return '空闲';  // 默认显示为空闲
            }
        },
        goToPage(page) {
            switch (page) {
                case 'index':
                    window.location.href = 'index.html';
                    break;
                case 'schedule':
                    window.location.href = 'schedule.html';
                    break;
                case 'records':
                    window.location.href = 'records.html';
                    break;
                case 'profile':
                    window.location.href = 'profile.html';
                    break;
            }
        },
        validateScheduleForm() {
            if (!this.scheduleForm.date) {
                alert('请选择日期');
                return false;
            }
            if (!this.scheduleForm.timeSlot) {
                alert('请选择时间段');
                return false;
            }
            if (!this.scheduleForm.type) {
                alert('请选择咨询类型');
                return false;
            }
            return true;
        },
        getTimeIndex(timeSlot) {
            const normalizedTimeSlot = timeSlot.replace('.', ':').toLowerCase();
            return this.timeSlots.findIndex(slot =>
                slot.toLowerCase() === normalizedTimeSlot
            );
        },
        getDayIndex(date) {
            const scheduleDate = new Date(date);
            const startDate = new Date(this.weekStart);
            // 重置时间部分以确保准确比较日期
            scheduleDate.setHours(0, 0, 0, 0);
            startDate.setHours(0, 0, 0, 0);
            const diffDays = Math.floor((scheduleDate - startDate) / (1000 * 60 * 60 * 24));
            return diffDays >= 0 && diffDays < 7 ? diffDays : -1;
        },
        getSlotClass(slot) {
            if (!slot) return 'slot-empty';

            const classes = ['schedule-slot'];

            switch (slot.status) {
                case 'available':
                    classes.push('slot-available');
                    break;
                case 'selected':
                    classes.push('slot-selected');  // 为可被约状态添加独立的样式类
                    break;
                case 'booked':
                    classes.push('slot-booked');
                    break;
                case 'cancelled':
                    classes.push('slot-cancelled');
                    break;
                default:
                    classes.push('slot-available');
            }

            if (slot.type) {
                classes.push(`type-${slot.type}`);
            }

            return classes.join(' ');
        },
        isPastDate(dateStr) {
            if (!dateStr) return false;
            const today = new Date();
            today.setHours(0, 0, 0, 0);
            const checkDate = new Date(dateStr);
            checkDate.setHours(0, 0, 0, 0);
            return checkDate < today;
        },
        async fetchWeeklySchedule() {
            try {
                const response = await fetch(`/api/therapist/schedule/weekly?startDate=${this.weekStart}`, {
                    headers: {
                        'Authorization': localStorage.getItem('token')
                    }
                });

                const result = await response.json();

                // 检查返回的状态码
                if (result.code === "200") {
                    console.log('获取到的排班数据:', result.data);
                    this.updateScheduleDisplay(result.data);
                } else {
                    throw new Error(result.message || '获取排班失败');
                }
            } catch (error) {
                console.error('获取排班失败:', error);
                alert('当前时间已失效,请重新选择时间');
            }
        },
        async submitSchedule() {
            if (!this.validateScheduleForm()) return;

            try {
                const response = await axios.post('/therapist/schedule', this.scheduleForm);

                if (response.data.code === "200") {
                    alert('排班添加成功');
                    this.closeModal();
                    await this.fetchWeeklySchedule();
                } else {
                    throw new Error(response.data.message);
                }
            } catch (error) {
                console.error('添加排班失败:', error);
                if (!error.message.includes('未登录')) {
                    alert(error.response?.data?.message || '当前时间已失效,请重新选择时间');
                }
            }
        },
        formatDisplayDate(dateStr) {
            const date = new Date(dateStr);
            return `${date.getMonth() + 1}月${date.getDate()}日`;
        },
        initializeScheduleGrid() {
            this.scheduleGrid = this.timeSlots.map(timeSlot => {
                return this.weekDays.map(day => ({
                    date: day.fullDate,
                    timeSlot: timeSlot,
                    status: null,
                    statusText: '',
                    type: null,
                    clientName: null
                }));
            }).flat();
        },
        normalizeTimeSlot(timeSlot) {
            if (!timeSlot) return '';
            const [start, end] = timeSlot.split('-');
            const normalizedStart = start.trim().padStart(5, '0');
            const normalizedEnd = end ? end.trim().padStart(5, '0') : '';
            return normalizedEnd ? `${normalizedStart}-${normalizedEnd}` : normalizedStart;
        },
        getSchedule(date, timeSlot) {
            return this.scheduleGrid.find(schedule =>
                schedule.date === date &&
                schedule.timeSlot === timeSlot
            );
        },
        getSlotStatusText(date, timeSlot) {
            const schedule = this.getSchedule(date, timeSlot);
            return schedule?.statusText || '可预约';
        },
        getSlotType(date, timeSlot) {
            const schedule = this.getSchedule(date, timeSlot);
            return schedule?.type === 'online' ? '线上咨询' : '面对面咨询';
        },
        goToToday() {
            this.currentWeek = new Date();
            this.weekStart = this.formatDateForInput(this.getWeekStart(this.currentWeek));
            this.checkIsPastWeek();
            this.initializeCalendarData();
            this.fetchWeeklySchedule();
        },
        checkIsPastWeek() {
            const today = new Date();
            today.setHours(0, 0, 0, 0);
            const weekStart = this.getWeekStart(this.currentWeek);
            weekStart.setHours(0, 0, 0, 0);
            this.isPastWeek = weekStart < today;
        }
    },
    created() {
        this.initializeCalendarData();
        this.weekStart = this.formatDateForInput(this.getWeekStart(this.currentWeek));
        this.checkIsPastWeek();
        this.fetchWeeklySchedule();
    }
}).mount('#app') 